package com.example.demo8.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Classname PushCallback
 * @Description 消费监听类
 */
@Component
public class PushCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class);
    private static MqttClient client;
    @Autowired
    private MqttConfig mqttConfig;
    @Autowired
    private MqttPushClient mqttPushClient;

    @Override
    public void connectionLost (Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接断开，可以做重连");
        if (client == null || !client.isConnected()) {
            mqttConfig.getMqttPushClient();
        }
    }

    @Override
    public void messageArrived (String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        logger.info("接收消息主题 : " + topic);
        logger.info("接收消息Qos : " + mqttMessage.getQos());
        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));
        try {
            JSONObject jsonObject = JSON.parseObject(new String(mqttMessage.getPayload()));
        } catch (Exception e) {
            System.err.println("===未知消息格式：" + new String(mqttMessage.getPayload()));
            return;
        }
        if (topic.startsWith("device_info")) {
            //添加设备信息
            logger.info("添加设备信息");
        } else if (topic.startsWith("status")) {
            //状态
            logger.info("状态");
        } else if (topic.startsWith("setting")) {
            // 设置
            logger.info("设置");
        } else if (topic.startsWith("offline")) {
            //离线遗嘱
            logger.info("离线遗嘱");
        } else if (topic.startsWith("cmd")) {
            //发送指令
            logger.info("发送指令");
        }
    }

    @Override
    public void deliveryComplete (IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }
}